package com.interesting.base.http;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.json.JSONException;
import org.json.JSONObject;

import com.interesting.base.utils.Constant;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;

public class HttpUtil {

	public enum HttpCode {
		SUCCEED("000"), FAILD("001"), NONE("002");

		private String value;

		private HttpCode(String value) {
			this.value = value;
		}

		public String getValue() {
			return value;
		}

	}

	public static String post(Map<String, String> params) {
		Log.d("debug", "http-begin");
	
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpParams httpParams = client.getParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 4000);

		HttpPost httpPost = new HttpPost(Constant.URL);

		try {
			List<NameValuePair> vaules = new ArrayList<NameValuePair>();
			for (String key : params.keySet()) {
				vaules.add(new BasicNameValuePair(key, params.get(key)));
				
			}
			HttpEntity entity = new UrlEncodedFormEntity(vaules, HTTP.UTF_8);
			Log.d("TAG","tag"+ vaules.toString());

			httpPost.setEntity(entity);

			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				HttpEntity ent = response.getEntity();
				InputStream content = ent.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				Log.e("error", "Failed to http connect");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.d("debug", "http-end");
		return builder.toString();
	}

	public static void get(Map<String, String> fields) {
		// TODO Auto-generated method stub

	}

	public static JSONObject parseResult(String result) {
		JSONObject response = null;
		Log.d("TAG", result.toString());
		try {
			response = new JSONObject(result);
			String status = response.getString("succeed");
			if (status.equals(HttpCode.SUCCEED.getValue())) {
				return response;
			} else if (status.equals(HttpCode.FAILD.getValue())) {
				return null;
			} else if (status.equals(HttpCode.NONE.getValue())) {
				/*
				 * 
				 */
				return null;
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return response;
	}

	// post data whit image
	public static String postImage(Map<String, Object> fields) {
		try {

			HttpClient httpClient = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();

			HttpPost httpPost = new HttpPost(Constant.URL + "?act=" + (String) fields.get("act"));
			MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			// CompressFormat set up to JPG, you can change to PNG or whatever
			// you want;
			if (fields.get("photo") instanceof Bitmap) {
				((Bitmap) fields.get("photo")).compress(CompressFormat.JPEG, 60, bos);
			}
			byte[] data = bos.toByteArray();

			// sending a String param;
			for (Map.Entry<String, Object> entry : fields.entrySet()) {
				if (entry.getValue() instanceof String) {
					if (!((String) entry.getValue()).equals("act")) {
						String value = (String) entry.getValue();
						entity.addPart(entry.getKey(), new StringBody(value, Charset.forName(HTTP.UTF_8)));
					}
				}
			}
			// sending a Image;
			// note here, that you can send more than one image, just add
			// another param, same rule to the String;
			if (fields.get("photo") instanceof Bitmap) {
				entity.addPart("photo", new ByteArrayBody(data, "temp.jpg"));
			}
			httpPost.setEntity(entity);
			HttpResponse response = httpClient.execute(httpPost, localContext);
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
			String sResponse = reader.readLine();
			return sResponse;
		} catch (Exception e) {
			Log.v("myApp", "Some error came up");
		}
		return "";
	}
	
}
